package org.jeecg.modules.demand.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demand.entity.Demand;
import org.jeecg.modules.demand.entity.DemandTree;
import org.jeecg.modules.demand.service.IDemandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 需求
 * @Author: jeecg-boot
 * @Date:   2023-08-29
 * @Version: V1.0
 */
@Api(tags="需求")
@RestController
@RequestMapping("/demand/demand")
@Slf4j
public class DemandController extends JeecgController<Demand, IDemandService> {
	@Autowired
	private IDemandService demandService;
	
	/**
	 * 分页列表查询
	 *
	 * @param demand
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "需求-分页列表查询")
	@ApiOperation(value="需求-分页列表查询", notes="需求-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Demand demand,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Demand> queryWrapper = QueryGenerator.initQueryWrapper(demand, req.getParameterMap());
		Page<Demand> page = new Page<Demand>(pageNo, pageSize);
		IPage<Demand> pageList = demandService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@GetMapping("/getDemandTree/{id}")
	public Result<?> getDemandTree(@PathVariable("id") String projectId){
		QueryWrapper<Demand> wrapper = new QueryWrapper<>();
		wrapper.eq("project_id", projectId);
		List<Demand> list = demandService.list(wrapper);
		List<DemandTree> demandTree = DemandToTree(list);
		return Result.OK(demandTree);
	}

	public static List<DemandTree> DemandToTree(List<Demand> list) {
		Map<String, DemandTree> demandMap = new HashMap<>();
		List<DemandTree> roots = new ArrayList<>();
		// 首先将所有节点放入哈希表中，通过节点 id 进行索引
		for (Demand demand : list) {
			DemandTree demandTree = new DemandTree();
			demandTree.setKey(demand.getId()).setTitle(demand.getTitle()).setFinish(demand.getFinish()).setChildren(new ArrayList<>());
			demandMap.put(demand.getId(), demandTree);
		}
		for (Demand demand : list) {
			DemandTree demandTree = demandMap.get(demand.getId()); // 从 demandMap 中获取对应的 DemandTree 对象
			if (demandTree != null) {
				String parentId = demand.getParentId();
				DemandTree parent = demandMap.get(parentId);
				if (parent != null) {
					parent.getChildren().add(demandTree);
				} else {
					roots.add(demandTree);// 如果没有找到父节点，则为根节点
				}
			}
		}
//		log.info("roots: {}", roots);
		return roots;
	}

	@PostMapping("/finish/{id}")
	public Result<?> finish(@PathVariable("id") String id){
		UpdateWrapper<Demand> wrapper = new UpdateWrapper<>();
		wrapper.set("finish", true);
		wrapper.eq("id", id);
		demandService.update(wrapper);
		return Result.OK("修改成功!");
	}

	@PostMapping("/unFinish/{id}")
	public Result<?> unFinish(@PathVariable("id") String id){
		UpdateWrapper<Demand> wrapper = new UpdateWrapper<>();
		wrapper.set("finish", false);
		wrapper.eq("id", id);
		demandService.update(wrapper);
		return Result.OK("修改成功!");
	}

	/**
	 *   添加
	 *
	 * @param demand
	 * @return
	 */
	@AutoLog(value = "需求-添加")
	@ApiOperation(value="需求-添加", notes="需求-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody Demand demand) {
		demandService.save(demand);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param demand
	 * @return
	 */
	@AutoLog(value = "需求-编辑")
	@ApiOperation(value="需求-编辑", notes="需求-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody Demand demand) {
		demandService.updateById(demand);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "需求-通过id删除")
	@ApiOperation(value="需求-通过id删除", notes="需求-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		List<Demand> list = demandService.list();
		List<String> childIds = new ArrayList<>();
		List<String> ids = getAllChildIds(list, id, childIds);
		demandService.removeByIds(ids);
		return Result.OK("删除成功!");
	}

	private List<String> getAllChildIds(List<Demand> list, String parentId, List<String> childIds) {
		childIds.add(parentId);
		for (Demand demand : list){
			if (parentId.equals(demand.getParentId())){
				getAllChildIds(list, demand.getId(), childIds);
			}
		}
		return childIds;
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "需求-批量删除")
	@ApiOperation(value="需求-批量删除", notes="需求-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.demandService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "需求-通过id查询")
	@ApiOperation(value="需求-通过id查询", notes="需求-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Demand demand = demandService.getById(id);
		if(demand==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(demand);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param demand
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Demand demand) {
        return super.exportXls(request, demand, Demand.class, "需求");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Demand.class);
    }

}
